<template>
  <div>
    <el-button @click="exportToWord">导出到 Word</el-button>
    <el-button @click="exportToPdf">导出到 PDF</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { saveAs } from 'file-saver';
import { Packer, Paragraph, Table, TableRow, TableCell, Document } from 'docx';
import { ref } from "vue";
import jsPDF from 'jspdf'
import autoTable from 'jspdf-autotable'
import '@/utils/simhei-normal'

const tableHeader = ref([
  '2021-01-02',
  '2021-01-02',
  '2021-01-02',
])
const tableData = ref([
  { name: '张三', age: 25, address: 'abg' },
  { name: '李四', age: 30, address: '上海市' },
  { name: '王五', age: 28, address: '广州市' },
  { name: '王五', age: 28, address: '广州市' },
  { name: '王五', age: 28, address: '广州市' },
  { name: '王五', age: 28, address: '广州市' },
  { name: '王五', age: 28, address: '广州市' },
]);

const exportToWord = () => {
  const tableH = new Table({
    rows:  [new TableRow({
      children: tableHeader.value.map(d => {
        return new TableCell({ children: [new Paragraph(d)] })
      })
    })]
  });
  const table = new Table({
    rows: tableData.value.map(item => new TableRow({
      children: [
        new TableCell({ children: [new Paragraph(item.name)] }),
        new TableCell({ children: [new Paragraph(item.age.toString())] }),
        new TableCell({ children: [new Paragraph(item.address)] })
      ]
    }))
  });

  const doc = new Document({
    sections: [{
      children: [
        new Paragraph("表格数据"),
        tableH,
        table
      ],
    }],
  });

  Packer.toBlob(doc).then((blob) => {
    saveAs(blob, "tableData.docx");
  });
};


const exportToPdf = async () => {
  const doc = new jsPDF()
  doc.setFont('simhei');
  autoTable(doc, {
    head: [tableHeader.value],
    body:
      tableData.value.map(d => {
        return Object.values(d);
      }),
    styles: {
      font: 'simhei', //字体，如果不配置，表格中的中文仍会乱码
      textColor: [0, 0, 0],
    },
  })
  doc.save('table.pdf')
};
</script>

<style scoped lang="scss">

</style>